import type PageTable from '@/components/page-table.vue'
import useSystemStore from '@/stores/main/system'
import { ref, type Ref } from 'vue'

interface IUseTable {
  pageName: string
  editId?: Ref<number | null>
  editForm?: Ref<any>
  addForm?: Ref<any>
  formRef?: any
  pageDialogRef?: any
  pageSearchRef?: any
}
export default function useTable(options: IUseTable) {
  const systemStore = useSystemStore()
  const pageTableRef = ref<InstanceType<typeof PageTable>>()

  const confirm = (otherInfo = {}) => {
    options.formRef.value.validate().then((valid: any) => {
      if (valid !== true) return
      const queryInfo = {
        page: pageTableRef.value!.pagination.current,
        size: pageTableRef.value!.pagination.pageSize,
        ...options.pageSearchRef?.value.formData,
        ...otherInfo
      }
      if (options.editId?.value) {
        systemStore.editPageAction(
          options.pageName,
          options.editId.value,
          options.editForm!.value,
          queryInfo
        )
      } else {
        systemStore.addPageAction(options.pageName, options.addForm!.value, queryInfo)
      }
      options.formRef.value.reset()
      options.pageDialogRef.value.close()
    })
  }

  const search = (searchForm: any) => {
    const queryInfo = {
      page: pageTableRef.value!.pagination.current,
      size: pageTableRef.value!.pagination.pageSize,
      ...searchForm
    }
    systemStore.getPageListAction(options.pageName, queryInfo)
  }

  return {
    confirm,
    search,
    pageTableRef
  }
}
